package com.atguigu.gulimall.auth.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.model.SocialUser;
import com.atguigu.common.model.vo.MemberResponseVo;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * 处理社交登录请求
 */
@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        //1、根据 code 换取 accessToken
        //https://api.weibo.com/oauth2/access_token?
        // client_id=YOUR_CLIENT_ID
        // &client_secret=YOUR_CLIENT_SECRET
        // &grant_type=authorization_code
        // &redirect_uri=YOUR_REGISTERED_REDIRECT_URI
        // &code=CODE
        HashMap<String, String> body = new HashMap<>();
        body.put("client_id", "4064978942");//应用id，固定的
        body.put("client_secret", "060fb0dabe7e58aacf783dc95ed242f4");//应用密钥，固定的
        body.put("grant_type", "authorization_code");
        body.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        body.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), null, body);

        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道是哪个社交用户
            //1、如果当前用户是第一次进网站，自动注册一个会员信息账号，以后该账号对应指定会员
            //登录或者注册这个用户
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getCode() == 0) {
                //2、登录成功，调回首页
                MemberResponseVo memberResponseVo = r.getData(new TypeReference<MemberResponseVo>() {
                });
                log.info("登录成功，用户信息{}", memberResponseVo);
                session.setAttribute(AuthServerConstant.LOGIN_USER, memberResponseVo);
                return "redirect:http://gulimall.com";
            }
        }
        return "redirect:http://auth.gulimall.com/login";
    }
}
